<?php
class Modelo_ec extends Model {
    private $cart_name;       
    private $items = array(); 
    private $product_id;
    private $product_name;
    private $product_seo;
    private $product_desc;
    private $product_price;
    private $product_sku;
    private $vendor_id;
    private $product_in_stock;
    private $product_full_image;
    private $product_discount_id;
    private $product_publish;
    private $custom_attribute;
    private $category_name;
    private $category_parent_id;
    private $breadcrumb = array();
    public  $vista_breadcrumb;

    function Modelo_ec() {
        parent::Model();
    }

    function carro($name) {
        $this->cart_name = $name['nombre'];
        if(isset($_SESSION[$this->cart_name]))
            $this->items = $_SESSION[$this->cart_name];
    }

    function getItemQuantity($order_code) {
        if (!empty($this->items[$order_code])) {
            $cantidad = $this->items[$order_code];
        }else {
            $cantidad = 0;
        }
        return (int) $cantidad;
    }

    function setItemQuantity($order_code, $quantity) {
        $this->items[$order_code] = $quantity;
    }

    function save() {
        $this->clean();
        $_SESSION[$this->cart_name] = $this->items;
    }

    function clean() {
        foreach ( $this->items as $order_code=>$quantity ) {
            if ( $quantity < 1 )
                unset($this->items[$order_code]);
        }
    }

    function hasItems() {
        return (bool) $this->items;
    }

    function getItems() {
        return $this->items;
    }

    function getItemPrice($order_code) {
        $CI =& get_instance();
        $CI->load->database();
        $id = $order_code;

        //calculo de precio
        $query = $CI->db->query("SELECT product_price FROM product_price WHERE product_id='".$id."'");
        if ($query->num_rows() > 0) {
            $row=$query->row();
            $precio = $row->product_price;
        }

        $query = $CI->db->query("SELECT category_id FROM product_category_xref WHERE product_id='".$id."'");
        if ($query->num_rows() > 0) {
            $row=$query->row();
            $category_id = $row->category_id;
        }

        $query = $CI->db->query("SELECT category_parent_id FROM category_xref WHERE category_child_id='".$category_id."'");
        if ($query->num_rows() > 0) {
            $row=$query->row();
            $category_parent_id = $row->category_parent_id;
        }

        //echo "SELECT products_per_row FROM category WHERE category_id='".$category_id."'";
        $query = $CI->db->query("SELECT products_per_row_1 FROM category WHERE category_id='".$category_id."'");
        if ($query->num_rows() > 0) {
            $row=$query->row();
            $ganancia_categoria = $row->products_per_row_1;
        }

        $query = $CI->db->query("SELECT products_per_row_1 FROM category WHERE category_id='".$category_parent_id."'");
        if ($query->num_rows() > 0) {
            $row=$query->row();
            $ganancia_sub_categoria = $row->products_per_row_1;
        }

        $ganancia = (($ganancia_categoria + $ganancia_sub_categoria) / 100) + 1;
        $product_price = $precio * $ganancia;

        return number_format($product_price,2,'.',',');
    }

    function getItemCode($order_code) {
        // This is where the code that retrieves product names
        // goes. We'll just return something generic for this tutorial.
        //        return 'My Product (' . $order_code . ')';
        $CI =& get_instance();
        $CI->load->database();
        $query = $CI->db->query("SELECT product_sku FROM product WHERE product_id=".$order_code);
        $row2=$query->row();
        return $row2->product_sku;
    }

    function getItemName($order_code) {
        // This is where the code that retrieves product names
        // goes. We'll just return something generic for this tutorial.
        //        return 'My Product (' . $order_code . ')';
        $CI =& get_instance();
        $CI->load->database();
        $query = $CI->db->query("SELECT product_name FROM product WHERE product_id=".$order_code);
        $row2=$query->row();
        return $row2->product_name;
    }

    function saveCar($orden_compra,$customer_note) {
        $CI =& get_instance();
        $CI->load->database();
        $order_subtotal=0;

        foreach ( $this->items as $order_code=>$quantity ) {
            $query = $CI->db->query("SELECT product_price FROM product_price WHERE product_id=".$order_code);
            if ($query->num_rows() > 0) {
                $row2=$query->row();
                $precio = $row2->product_price;
            }
            $order_subtotal = $order_subtotal + ($precio*$this->items[$order_code]);
        }

        $query = $CI->db->query("SELECT extra_field_1, extra_field_2, extra_field_3, extra_field_5 FROM users WHERE id=".$CI->session->userdata('id'));

        $order_total = $order_subtotal;
        if ($query->num_rows() > 0) {
            $row=$query->row();
            $bonificacion = ($order_total * $row->extra_field_3) / 100;
            $iva = (($order_total - $bonificacion) * $row->extra_field_1) / 100;
            $percepcion = (($order_total - $bonificacion) * $row->extra_field_2) / 100;
            $total = $order_total - $bonificacion + $iva + $percepcion;
        }
        if ($order_total !=0) {
            $query = $CI->db->query("INSERT INTO orders set user_id='".$CI->session->userdata('id')."', vendor_id='1', order_number='', order_total='".$total."', order_subtotal='".$order_total."', order_tax='".$iva."', order_discount='".$bonificacion."', order_status='P', cdate=".time().", mdate=".time().", customer_note='".$customer_note."', orden_compra='".$orden_compra."', ip_address='".$_SERVER['REMOTE_ADDR']."'");
            //ultimo registro ingresado
            $nuerodeorden = $CI->db->insert_id();
            foreach ( $this->items as $order_code=>$quantity ) {
                //vuelvo a agregar ceros
                $product_sku = sprintf("%05s",$this->getItemCode($order_code));
                $query = $CI->db->query("INSERT INTO order_item set order_id='".$nuerodeorden."', vendor_id='1', product_id='".$order_code."', order_item_sku='".$product_sku."', order_item_name='".$this->getItemName($order_code)."', product_quantity='".$quantity."', product_item_price='".$this->getItemPrice($order_code)."', order_status='P', cdate=".time().", mdate=".time()."");
            }

            $this->erase(); // luego de grabar el carrito lo borramos
        }
        return $nuerodeorden;
    }
    
    function erase() {
        foreach ( $this->items as $order_code=>$quantity ) {
            unset($this->items[$order_code]);
        }
        $_SESSION[$this->cart_name] = $this->items;
    }

    function get_breadcrumb($id) {
        while ($id !=0) {
            $query = $this->db->query("SELECT category_parent_id FROM category_xref WHERE category_child_id='".$id."'");
            if ($query->num_rows() > 0)
                $row=$query->row();
            $this->category_parent_id  =  $row->category_parent_id;

            $query = $this->db->query("SELECT category_name FROM category WHERE category_id='".$id."'");
            if ($query->num_rows() > 0)
                $row=$query->row();
            $this->category_name  =  $row->category_name;
            $this->breadcrumb[$id] = $this->category_name;
            $id = $this->category_parent_id;
        }

        ksort($this->breadcrumb);
        $i=0;
        foreach ($this->breadcrumb as $key => $row) {
            if ($i==0) {
                $this->vista_breadcrumb = '<a href='.base_url().'index.php/ecommerce_empresa1/pedido1/'.$key.'>> '.$row.'</a>';
            }else {
                $this->vista_breadcrumb .= '<a href='.base_url().'index.php/ecommerce_empresa1/pedido1/'.$key.'> / '.$row.'</a>';
            }
            $i++;
        }
    }

    /**
     * Llena variables con datos del producto
     */
    function get_articulo($id) {
        $query = $this->db->query("SELECT * FROM product WHERE product_id='".$id."'");
        if ($query->num_rows() > 0)
            $row=$query->row();
        $this->product_id   = $id;
        $this->product_sku  =  $row->product_sku;
        $this->product_name = $row->product_name;

        //calculo de precio
        $query = $this->db->query("SELECT product_price FROM product_price WHERE product_id='".$id."'");
        if ($query->num_rows() > 0) {
            $row=$query->row();
            $precio = $row->product_price;
        }

        $query = $this->db->query("SELECT category_id FROM product_category_xref WHERE product_id='".$id."'");
        if ($query->num_rows() > 0) {
            $row=$query->row();
            $category_id = $row->category_id;
        }

        $query = $this->db->query("SELECT category_parent_id FROM category_xref WHERE category_child_id='".$category_id."'");
        if ($query->num_rows() > 0) {
            $row=$query->row();
            $category_parent_id = $row->category_parent_id;
        }

        //echo "SELECT products_per_row FROM category WHERE category_id='".$category_id."'";
        $query = $this->db->query("SELECT products_per_row_1 FROM category WHERE category_id='".$category_id."'");
        if ($query->num_rows() > 0) {
            $row=$query->row();
            $ganancia_categoria = $row->products_per_row_1;
        }

        $query = $this->db->query("SELECT products_per_row_1 FROM category WHERE category_id='".$category_parent_id."'");
        if ($query->num_rows() > 0) {
            $row=$query->row();
            $ganancia_sub_categoria = $row->products_per_row_1;
        }

        $ganancia = (($ganancia_categoria + $ganancia_sub_categoria) / 100) + 1;
        $this->product_price = number_format($precio * $ganancia,2,'.',',');
    }


    /**
     * Retorna precio del articulo
     */
    function get_precio($id) {

        //calculo de precio
        $query = $this->db->query("SELECT product_price FROM product_price WHERE product_id='".$id."'");
        if ($query->num_rows() > 0) {
            $row=$query->row();
            $precio = $row->product_price;
        }

        $query = $this->db->query("SELECT category_id FROM product_category_xref WHERE product_id='".$id."'");
        if ($query->num_rows() > 0) {
            $row=$query->row();
            $category_id = $row->category_id;
        }

        $query = $this->db->query("SELECT category_parent_id FROM category_xref WHERE category_child_id='".$category_id."'");
        if ($query->num_rows() > 0) {
            $row=$query->row();
            $category_parent_id = $row->category_parent_id;
        }

        //echo "SELECT products_per_row FROM category WHERE category_id='".$category_id."'";
        $query = $this->db->query("SELECT products_per_row_1 FROM category WHERE category_id='".$category_id."'");
        if ($query->num_rows() > 0) {
            $row=$query->row();
            $ganancia_categoria = $row->products_per_row_1;
        }

        $query = $this->db->query("SELECT products_per_row_1 FROM category WHERE category_id='".$category_parent_id."'");
        if ($query->num_rows() > 0) {
            $row=$query->row();
            $ganancia_sub_categoria = $row->products_per_row_1;
        }

        $ganancia = (($ganancia_categoria + $ganancia_sub_categoria) / 100) + 1;
        $this->product_price = $precio * $ganancia;

    }

    /**
     * Retorna nombre de la categoria
     */
    function get_nombre_categoria($id) {
        $query = $this->db->query("SELECT category_name FROM category WHERE category_id='".$id."'");
        if ($query->num_rows() > 0)
            $row=$query->row();
        $this->category_name = $row->category_name;
    }

    /**
     * Retorna datos listado de categorias
     */
    function get_categorias() {
        $query['consulta2'] = $this->db->query("SELECT category_child_id FROM category_xref WHERE category_parent_id = 0");
        return $query;
    }

    /**
     * Retorna datos para el banner id es el numero de banner a mostrar
     */
    function get_banners($id) {
        $query = $this->db->query("SELECT texto FROM banners WHERE peso ='".$id."'");
        if ($query->num_rows() > 0)
            $row=$query->row();
        $content = $row->texto;
        $sustituye = array("(\r\n)", "(\n\r)", "(\n)", "(\r)");
        $content = preg_replace($sustituye, "", $content);
        $this->banners = $content;
    }

    /**
     * Retorna datos para el contenido del home
     * lista productos en ofertas por ahora ...
     */
    function get_contenido_home() {
        $query['consulta']  = $this->db->query("SELECT product_id FROM product WHERE product_discount_id = 1");
        $query['consulta1'] = $this->db->query("SELECT product_id FROM product WHERE product_discount_id = 2");
        // poner otra cosulta para los mas vendidos por ahora lo sacamos con product_discont igual a 2
        return $query;
    }


}
?>
